package com.heo.protocol.packet;

import org.apache.log4j.Logger;
import com.heo.util.ByteHelper;

/**
 * 服务器主动下发，给设备发启动指令
 * 
 * @author chichi
 */
public class UpdateFirmwareReq extends BasePacket
{
  private int BODY_LENGTH = 40;// 包体长40
  private static final String PACKET_NAME = "[升级固件请求包]";

  private static Logger log = Logger.getLogger(UpdateFirmwareReq.class);

  private String firmwareVer;// 固件版本，4个字节
  private long firmwareLength;// 固件总长度，4个字节
  private String firmwareMD5;// 固件MD5值，32个字节

  /**
   * 通过网络传过来的流构建对象
   * 
   * @param totalLength
   * @param commandId
   * @param sequenceId
   * @param body
   * @throws Exception
   */
  public UpdateFirmwareReq(String logHeader, SocketPacket packet) throws Exception
  {
    super.copyPacket(logHeader, PACKET_NAME, packet);
    makeBody();
  }

  @Override
  public int getTotalLength()
  {
    return super.HEAD_LENGTH + BODY_LENGTH;
  }

  public UpdateFirmwareReq(int sequenceId) throws Exception
  {
    super(PACKET_NAME);
    super.sequenceId = sequenceId;
    super.totalLength = (short) (HEAD_LENGTH + BODY_LENGTH);
    super.commandId = DeviceCommand.FIRMWARE_NOTICE_REQ;
    super.sendCount = 1;
  }

  @Override
  public byte[] getPacketBody()
  {
    return ByteHelper.margeByte(firmwareVer.getBytes(), ByteHelper.intToByteArray((int) firmwareLength), firmwareMD5.getBytes(),null, null, null, null, null, null, null);
  }

  @Override
  public void makeBody() throws Exception
  {
    if (packetBody.length != BODY_LENGTH)
    {
      log.error(super.logHeader + super.packetName + "数据包长度错误。包体长度应该为：" + BODY_LENGTH + "个字节。");
      throw new Exception(super.logHeader + super.packetName + "数据包长度错误。包体长度应该为：" + BODY_LENGTH + "个字节。");
    }
    firmwareVer = ByteHelper.byteToString(packetBody, 0, 4, (byte) 0);
    firmwareLength = ByteHelper.byteToInt(packetBody, 4, 4);
    firmwareMD5 = ByteHelper.byteToString(packetBody, 8, 32, (byte) 0);
    log.debug(super.logHeader + super.packetName + "数据包解析成功。");
  }

  public static void main(String[] args)
  {

  }

  public String getFirmwareVer()
  {
    return firmwareVer;
  }

  public void setFirmwareVer(String firmwareVer)
  {
    this.firmwareVer = firmwareVer;
  }

  public long getFirmwareLength()
  {
    return firmwareLength;
  }

  public void setFirmwareLength(long firmwareLength)
  {
    this.firmwareLength = firmwareLength;
  }

  public String getFirmwareMD5()
  {
    return firmwareMD5;
  }

  public void setFirmwareMD5(String firmwareMD5)
  {
    this.firmwareMD5 = firmwareMD5;
  }

  

}
